package system

import (
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"main.go/global"
	"main.go/model/common/request"
	"main.go/model/common/response"
	"main.go/model/system"
	systemReq "main.go/model/system/request"
	"main.go/utils"
)

type UploadFileApi struct{}

func (a *UploadFileApi) Create(c *gin.Context) {
	var f *system.SysFileUploadFile
	ossType := c.DefaultQuery("ossType", "")
	_, header, err := c.Request.FormFile("file")

	if err != nil {
		global.EVA_LOG.Error("接收文件失败!", zap.Error(err))
		response.FailWithMessage("接收文件失败", c)
		return
	}
	f, err = uploadFileService.UploadFile(header, ossType) // 文件上传后拿到文件路径
	if err != nil {
		global.EVA_LOG.Error("上传失败!", zap.Error(err))
		response.FailWithMessage("上传失败", c)
		return
	}
	response.OkWithDetailed(f, "上传成功", c)
}
func (a *UploadFileApi) Delete(c *gin.Context) {
	var reqId request.GetById
	err := c.ShouldBindJSON(&reqId)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(reqId, utils.IdVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	jwtId := utils.GetUserID(c)
	if jwtId == uint(reqId.ID) {
		response.FailWithMessage("删除失败, 自杀失败", c)
		return
	}
	err = uploadFileService.Delete(reqId.ID)
	if err != nil {
		global.EVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
		return
	}
	response.OkWithMessage("删除成功", c)

}

func (a *UploadFileApi) Update(c *gin.Context) {
	var data system.SysFileUploadFile
	err := c.ShouldBindJSON(&data)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	_, err = uploadFileService.Update(&data)
	if err != nil {
		global.EVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
		return
	}

	response.Ok(c)
}

func (a *UploadFileApi) List(c *gin.Context) {
	var pageInfo systemReq.SysFileUploadFileListReq
	err := c.ShouldBindJSON(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	err = utils.Verify(pageInfo, utils.PageInfoVerify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	list, total, err := uploadFileService.List(&pageInfo)
	if err != nil {
		global.EVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
		return
	}
	response.OkWithDetailed(response.PageResult{
		List:     list,
		Total:    total,
		Page:     pageInfo.Page,
		PageSize: pageInfo.PageSize,
	}, "获取成功", c)
}
